package cn.geminis.core.util;

import cn.geminis.core.exception.CommonException;
import lombok.NonNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @author Allen
 */
public class FileUtils {

    private FileUtils() {
    }

    public static void writeFile(@NonNull String filename, @NonNull byte[] data) {
        var file = new File(filename);
        if (!file.exists() && file.getParentFile() != null) {
            file.getParentFile().mkdirs();
        }

        try (var stream = new FileOutputStream(filename)) {
            stream.write(data);
        } catch (Exception e) {
            throw new CommonException("写文件错误", e);
        }
    }

    public static byte[] readFile(@NonNull String filename) {
        var file = new File(filename);
        if (!file.exists()) {
            return null;
        }

        var fileLen = (int) file.length();
        var data = new byte[fileLen];

        try (var stream = new FileInputStream(file)) {
            stream.read(data);
            return data;
        } catch (Exception e) {
            throw new CommonException("读取文件错误", e);
        }
    }
}
